package com.qkbb.admin.kuibu.qkbb.imageloader;

import java.net.URLEncoder;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * @author DigHammer
 * */

public class HttpUtil {

	public static boolean hasInternet(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context
				.getApplicationContext().getSystemService(
						Context.CONNECTIVITY_SERVICE);
		if (manager == null) {
			return false;
		}
		NetworkInfo networkinfo = manager.getActiveNetworkInfo();
		if (networkinfo == null || !networkinfo.isAvailable()) {
			return false;
		}
		return true;
	}

	private static String encodeArgumentAndPath(String urlPart)
			throws Exception {
		String splitRegex = "[/&=? ]";
		String[] split = urlPart.split(splitRegex);
		String newUrlPart = new String(urlPart);

		for (String part : split) {
			newUrlPart = newUrlPart.replace(part,
					URLEncoder.encode(part, "UTF-8"));
		}

		newUrlPart = newUrlPart.replaceAll(" ", "%20");
		return newUrlPart;
	}

	public static String encodeUTF8(String string) {
		String[] split = string.split("^(https?://)?[^/]+(:\\d+)?/");
		String ret = null;
		if (split != null && split.length > 0) {
			int cutLen = string.length() - split[1].length();
			try {
				ret = string.substring(0, cutLen)
						+ encodeArgumentAndPath(split[1]);
			} catch (Exception e) {
				e.printStackTrace();
				ret = string;
			}
		} else {

		}
		return ret;
	}
}
